package de.hs_mannheim.vem.ajchat.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import de.hs_mannheim.vem.ajchat.ClientApi;
import de.hs_mannheim.vem.ajchat.ClientApi.ClientApiObserver;

public class Client extends JFrame implements ClientApiObserver {
	private static final long		serialVersionUID	= -3349101474718510841L;
	private final JEditorPane		receive				= new JEditorPane();
	final JTextArea					send				= new JTextArea();
	private final JButton			sendButton			= new JButton("Send");
	final ClientApi					api;

	private final ActionListener	listener			= new ActionListener() {
															@Override
															public void actionPerformed(final ActionEvent e) {
																api.send(send.getText());
															}
														};

	public Client(final ClientApi api) {
		this.api = api;
		api.observers.add(this);
		sendButton.addActionListener(listener);
		setLayout(new BorderLayout());
		add(new JScrollPane(receive), BorderLayout.CENTER);
		final JPanel jPanel = new JPanel(new BorderLayout());
		jPanel.add(send, BorderLayout.CENTER);
		jPanel.add(sendButton, BorderLayout.EAST);
		add(jPanel, BorderLayout.SOUTH);
		setPreferredSize(new Dimension(640, 480));
		receive.setEditable(false);
		pack();
	}

	@Override
	public void dataChanged() {
		final StringBuilder sb = new StringBuilder();
		for (final String[] line : api.list) {
			sb.append(line[0]).append("\t").append(line[1]).append("\n");
		}
		receive.setText(sb.toString());
	}
}
